package com.tsfyun.scm.config.mock;

import feign.Client;
import feign.Request;
import feign.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient;

import java.io.IOException;
import java.net.URI;

/**
 * @Description:
 * @CreateDate: Created in 2021/12/10 10:50
 */
public class MockLoadBalancerFeignClient extends LoadBalancerFeignClient {

    @Value("${mock.url:''}")
    private String mockUrl;

    public MockLoadBalancerFeignClient(Client delegate, CachingSpringLoadBalancerFactory lbClientFactory, SpringClientFactory clientFactory) {
        super(delegate, lbClientFactory, clientFactory);
    }

    public Response execute(Request request, Request.Options options) throws IOException {
        URI asUri = URI.create(request.url());
        String clientName = asUri.getHost();
        String targetUrl = mockUrl;
        String newUrl = request.url().replace(clientName, targetUrl);
        Request newRequest = Request.create(request.httpMethod(),newUrl,request.headers(),request.requestBody());
        return super.getDelegate().execute(newRequest,options);
    }

}
